import { Router } from 'express';
import { db } from '../utils/db.js';
import { requireAuth, requireRole } from '../utils/auth.js';

const router = Router();

router.post('/', requireRole('BIDDER'), (req, res) => {
  const { tender_id, product_batch, production_date, expiry_date, total_amount, deposit_paid_date } = req.body;
  const tender = db.prepare('SELECT * FROM tenders WHERE id = ?').get(tender_id);
  if (!tender) {
    return res.status(404).render('error', { message: '未找到招标项目' });
  }
  const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.session.user.id);
  db.prepare(
    `INSERT INTO bids (bid_date, bidder_id, legal_person, phone, tender_id, product_batch, production_date, expiry_date, total_amount, deposit_paid_date)
     VALUES (datetime('now'),?,?,?,?,?,?,?,?,?)`
  ).run(
    req.session.user.id,
    user.legal_person || null,
    user.phone || null,
    tender_id,
    product_batch || null,
    production_date || null,
    expiry_date || null,
    Number(total_amount),
    deposit_paid_date || null
  );
  res.redirect('/bids/my');
});

router.get('/my', requireRole('BIDDER'), (req, res) => {
  const bids = db
    .prepare(
      `SELECT b.*, t.tender_code, t.drug_name
       FROM bids b JOIN tenders t ON b.tender_id = t.id
       WHERE b.bidder_id = ?
       ORDER BY b.created_at DESC`
    )
    .all(req.session.user.id);
  if (req.accepts('html')) {
    return res.render('bids', { bids, title: '我的投标' });
  }
  return res.json(bids);
});

router.get('/tender/:tenderId', requireAuth, (req, res) => {
  const tender = db.prepare('SELECT * FROM tenders WHERE id = ?').get(req.params.tenderId);
  if (!tender) {
    return res.status(404).render('error', { message: '未找到招标项目' });
  }
  if (!(req.session.user.role === 'ADMIN' || req.session.user.id === tender.created_by)) {
    return res.status(403).render('error', { message: '无权查看该投标列表' });
  }
  const bids = db
    .prepare(
      `SELECT b.*, u.company_name
       FROM bids b JOIN users u ON u.id = b.bidder_id
       WHERE b.tender_id = ?
       ORDER BY b.created_at DESC`
    )
    .all(req.params.tenderId);
  if (req.accepts('html')) {
    return res.render('bids', { bids, title: '招标投标列表' });
  }
  return res.json(bids);
});

export default router;


